import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
  // timeout: 5000
})

request.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers.Authorization = store.getters.token
  }
  // 对get请求的参数全部进行URL编码
  // const url = config.url

  // if (config.method === 'GET' && config.params) {
  //   url += '?'
  //   const keys = Object.keys(config.params)
  //   for (const key of keys) {
  //     url += `${key}=${encodeURIComponent(config.params[key])}&`
  //   }
  //   url = url.substring(0, url.length - 1)
  //   config.params = {}
  //   console.log(url, 'url')
  // }
  // config.url = url

  return config
}, error => {
  return Promise.reject(error)
})
request.interceptors.response.use(response => {
  return response
}, err => {
  if (err.response && err.response.status === 401) {
    store.dispatch('user/logout')
    router.push('/login')
    Message.error('token 超时')
  } else {
    Message.error(err.message)
  }
  return Promise.reject(err)
})

export default request
